<template>
  <div>
    <view
      v-if="contractStatus == 'success'"
      class="page-wrapper"
      style="padding-bottom: 78px"
    >
      <view class="imgs">
        <img mode="widthFix" :src="saveImgPath" style="width: 100vw" @click="onImgClick" />
      </view>
      <view v-if="!toSign">
        <view class="fixed-btm" v-if="!saveImgPath">
          <!-- <p>如果修改该合同内容，请返回源文件修改文件</p> -->
          <view class="btnrow">
            <button class="btn1 btn-preview" @click="preview">预览合同</button>
          </view>
        </view>
        <view class="fixed-btm" v-else>
          <!-- <p>如果修改该合同内容，请返回源文件修改文件</p> -->
          <view class="btnrow">
            <button class="btn1 btn-preview" @click="downloadContract">
              下载合同
            </button>
          </view>
        </view>
      </view>
      <view class="fixed-btm" v-else>
        <!-- <p>如果修改该合同内容，请返回源文件修改文件</p> -->
        <view class="btnrow">
          <template>
            <button
              v-if="!saveImgPath"
              :disabled="true"
              class="btn btn-sign"
              @click="addSignName"
            >
              去签署
            </button>
            <button
              class="btn btn-preview"
              v-if="!saveImgPath"
              @click="preview"
            >
              预览合同
            </button>
            <button
              class="btn1 btn-preview"
              v-if="saveImgPath"
              @click="addSignName"
            >
              去签署
            </button>
          </template>
        </view>
      </view>
    </view>
    <view v-if="contractStatus == 'error'" style="width: 100vw">
      <img
        src="/static/images/meiyoujilu.png"
        alt=""
        srcset=""
        class="contractStatusImg"
      />
      <view class="contractStatusTic">合同生成中，请稍后重新进入</view>
    </view>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { checkEleContractReq, setJpgToAppendix, getPersonalSignUrl } from "@/services/contract";
import { downloadFile } from "@/services/common";
export default {
  data() {
    return {
      contractlist: [],
      contractDetail: {},
      tempPath: "",
      savedFilePath: "",
      toSign: true,
      saveImgPath: "",
      contractStatus: "",
      isCheckFace: true
    };
  },
  computed: {
    ...mapState(["user", "settings", "site"]),
    companyId() {
      return this.site.companyId;
    }
  },
  onLoad: function (option) {
    console.log(option, "previewOption");
    let id = parseInt(option.contractId);
    let contractId = "";
    if(!isNaN(id) && typeof id == "number"){
      contractId = id.toString();
    }
    if (contractId) {
      uni.setStorageSync('contractIdP', contractId);
      if (option.status === "0" || option.status === 0) {
        this.contractDetail.contractId = contractId;
        this.checkEleContract(contractId);
        this.toSign = true;
      } else {
        this.checkEleContract(contractId);
        this.toSign = !option.status;
      }
    } else {
      this.contractStatus = "error";
    }
  },
  methods: {
    onImgClick() {
      uni.previewImage({
        urls: [this.saveImgPath],
        current: this.saveImgPath,
        success: res => {
          console.log("success", res);
        },
        fail: err => {
          console.log("fail", err);
        }
      });
    },
    onBeforeJump() {
      // 改动：跳转前添加标记
      // uni.setStorageSync('signFrom', "verifyByFace")
    },
    downloadContract() {
      uni.authorize({
        scope: "scope.writePhotosAlbum",
        success: () => {
          downloadFile(this.saveImgPath)
            .then((res) => {
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function () {
                  uni.showToast({
                    title: "保存成功",
                    duration: 1500,
                  });
                },
                fail: () => {
                  uni.showToast({
                    title: "保存失败",
                    duration: 1500,
                  });
                },
              });
            })
            .catch((err) => {
              uni.showToast({
                title: "保存失败",
                duration: 1500,
              });
            });
        },
        fail: () => {
          uni.showToast({
            title: "授权失败",
            duration: 1500,
          });
        },
      });
    },
    checkEleContract(id) {
      uni.showLoading({
        mask: true,
        title: "加载中...",
      });
      checkEleContractReq(id)
        .then((res) => {
          if (res) {
            if (res.name) {
              this.checkImg(res.name);
            } else {
              if (this.toSign) {
                this.checkPdf(res.path);
              } else {
                this.getSetJpgToAppendix(id);
              }
            }
            this.isCheckFace = res.contractVO.isCheckFace;
          } else {
            uni.hideLoading();
            this.contractStatus = "error";
          }
        })
        .catch((err) => {
          uni.hideLoading();
          this.contractStatus = "";
          console.log("err -->", err);
        });
    },
    getSetJpgToAppendix(id) {
      setJpgToAppendix(id)
        .then((res) => {
          console.log(res);
          if (res != 1) return false;
          checkEleContractReq(id)
            .then((res) => {
              if (res) {
                if (res.name) {
                  this.checkImg(res.name);
                } else {
                  uni.hideLoading();
                  this.contractStatus = "error";
                }
              } else {
                uni.hideLoading();
                this.contractStatus = "error";
              }
            })
            .catch((err) => {
              uni.hideLoading();
              this.contractStatus = "";
              console.log("err -->", err);
            });
        })
        .catch((err) => {
          uni.hideLoading();
          console.log("err -->", err);
        });
    },
    // 个人点去签署获取君子签签署链接浏览器跳转
    addSignName() {
      const data = {
        contractId: this.contractDetail.contractId,
        type: 1,
      };
      getPersonalSignUrl(data)
          .then((res) => {
            uni.setStorageSync("personalSignUrl", res);
            uni.navigateTo({
              url: '/pages/webView/personalSign'
            })
          })
          .catch((err) => {
            uni.hideLoading();
            console.log("err -->", err);
          });
    },
    checkImg(path) {
      this.saveImgPath = `${path}?token=` + uni.getStorageSync("token");
      this.contractStatus = "success";
      uni.hideLoading();
    },
    checkPdf(path) {
      console.log("path", path);
      downloadFile(path)
        .then((res) => {
          console.log("downloadFile", res);
          this.tempPath = res.tempFilePath;
          uni.saveFile({
            tempFilePath: this.tempPath,
            success: (fileRes) => {
              console.log("fileRes", fileRes);
              this.savedFilePath = fileRes.savedFilePath;
              this.contractStatus = "success";
              uni.hideLoading();
              this.preview();
            },
            fail: (fileErr) => {
              console.log("downloadFilefileErr", fileErr);
              uni.hideLoading();
              uni.showToast({
                title: fileErr,
                icon: "none",
                duration: 2000,
              });
            },
          });
        })
        .catch((err) => {
          console.log("downloadFilecatch", err);
          uni.hideLoading();
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },
    preview() {
      this.openFile(this.savedFilePath);
    },
    openFile(path) {
      uni.openDocument({
        filePath: path,
        fileType: "pdf",
        success: () => {},
        fail: (err) => {
          uni.showToast({
            title: err.message,
            icon: "none",
            duration: 2000,
          });
        },
      });
    },
  },
};
</script>
<style lang="scss">
.page-wrapper {
  width: 100%;
  .imgs {
    width: 100%;
    height: 100%;
    overflow-y: auto;
  }
  .contract-content {
    width: 100%;
    min-height: 100%;
    background: #fff;
    overflow: scroll;
  }
  .fixed-btm {
    width: 100%;
    position: fixed;
    bottom: 0;
    height: 78px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.08);
    padding-top: 12px;
    p {
      margin: 12px;
      font-size: 12px;
      font-weight: 400;
      color: rgba(192, 192, 192, 1);
      line-height: 17px;
      text-align: center;
    }
    .btnrow {
      height: 90px;
      display: flex;
      .btn {
        width: 165px;
        height: 50px;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 400;
        line-height: 50px;
      }
      .btn1 {
        width: 345px;
        height: 50px;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 400;
        line-height: 50px;
      }
      button::after {
        outline: none;
        border: none;
      }
      .btn-sign {
        color: rgba(153, 153, 153, 1);
        background: rgba(249, 249, 249, 1);
        border: 1px solid rgba(229, 229, 229, 1);
      }
      .btn-preview {
        color: rgba(255, 255, 255, 1);
        background: $theme;
      }
    }
  }
}
.contractStatusImg {
  display: block;
  width: 168px;
  height: 168px;
  margin: 104px auto 14px;
}
.contractStatusTic {
  width: 308px;
  height: 40px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(156, 156, 156, 1);
  line-height: 20px;
  display: block;
  margin: 0 auto;
  text-align: center;
}
</style>
